import {snCreateUIDom} from 'src/hrpub/common/utils/utils';
import MainTableOperator from '../components/MainRowOperator';

import {pageTo, base} from 'nc-lightapp-front';

import {addPkorgRefer} from '../../../public/functions/addCondition';
import {COMMON} from "../common/common";

export default class MainAction {
    constructor(comp) {
        this.comp = comp;
        if (comp.props.use) {
            comp.props.use.form('card');
            comp.props.use.editTable('list');
            comp.props.use.search('query');
            comp.props.use.form("hi_psndoc_ctrt");
            comp.props.use.form("bd_psndoc");
            comp.props.use.form("cardItem");
            comp.props.use.editTable('material');
            comp.props.use.editTable('hi_psndoc_work');
            comp.props.use.editTable('hi_psndoc_edu');
            comp.props.use.editTable('hi_psndoc_family');
        }
    }

    appConfig = COMMON.appConfig;

    appConfig2 = {
        pagecode: '60092010nccloud',
        appcode: '60092010'
    };

    // 获取多语
    getLanguage = () => {
        const {props} = this.comp;
        const {dispatch, MultiInit} = props;

        MultiInit.getMultiLang({
            moduleId: 'gx6008',
            domainName: 'hrtrn',
            callback: (json, status, init) => {
                dispatch({
                    type: 'emp/update',
                    payload: {
                        language: json
                    }
                });
            }
        });
    };

    // 获取模版信息
    getTemplate = () => {
        const {props} = this.comp;
        const {dispatch} = props;
        const reqData = [
            {
                rqUrl: '/platform/templet/querypage.do',
                rqJson: `{\n  \"pagecode\": \"${this.appConfig.pagecode}\",\n  \"appcode\": \"${this.appConfig
                    .appcode}\"\n}`,
                rqCode: 'template'
            },
            {
                rqUrl: '/platform/templet/querypage.do',
                rqJson: `{\n  \"pagecode\": \"${this.appConfig2.pagecode}\",\n  \"appcode\": \"${this.appConfig2
                    .appcode}\"\n}`,
                rqCode: 'data2'
            },
            {
                rqUrl: '/platform/appregister/queryallbtns.do',
                rqJson: `{\n  \"pagecode\": \"${this.appConfig.pagecode}\",\n  \"appcode\": \"${this.appConfig
                    .appcode}\"\n}`,
                rqCode: 'button'
            },
            {
                rqUrl: '/platform/appregister/queryappcontext.do',
                rqJson: `{\n  \"appcode\": \"${this.appConfig.appcode}\"}`,
                rqCode: 'context'
            }
        ];
        snCreateUIDom(this.appConfig, reqData, async (res) => {
            dispatch({
                type: 'emp/update',
                payload: {
                    showOrgRefer: true
                }
            });
            let data2 = res.data2;
            res.template.cardItem = data2['card'];
            if(data2['formrelation']['card']){
                data2['formrelation']['card'].forEach(key=>{
                    res.template[key] = data2[key]
                })
            }

            /*res.template.psninf = data2['psninf'];
            res.template.tailinfo = data2['tailinfo'];
            res.template.auditinfo = data2['auditinfo'];*/
            res.template.formrelation = data2['formrelation'];
            res.template.formrelation.cardItem = res.template.formrelation.card; //解决表格模板id冲突
            res.template.formrelation.card = [];
            res.template = this.initMeta(res.template, res.button);
            props.meta.setMeta(res.template, () => {
                addPkorgRefer(props, {});
            });
            props.button.setButtons(res.button);
        });
    };

    initMeta = (template, btnConf) => {
        const {props, action} = this.comp;
        const {emp} = props;
        let items = template['list'].items;
        //给表格增加操作列
        items.push({
            attrcode: 'operation',
            itemtype: 'customer',
            label: emp.language['gx6008-000046'] /* 国际化处理： 操作*/,
            width: '260px',
            //textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                let workState = record.values['workflow_state'].value;
                let btn = [];
                if (workState === '7') {
                    btn = ['chgbegindate', 'handle', 'reject'];
                } else if (workState === '102') {
                    btn = ['missremind', 'confreceive'];
                }
                return (
                    /*<MainTableOperator
                        btnConf={btnConf}
                        language={emp.language}
                        onClick={action.tableAct.rowClickHandle}
                        record={record}
                        index={index}
                    />*/
                    <div className="currency-opr-col">
                        {props.button.createOprationButton(btn,
                            {
                                area: 'list',
                                buttonLimit :2,
                                onButtonClick: (props, id, e) => {
                                    action.tableAct.rowClickHandle(id, record, index)
                                }
                            }
                        )}
                    </div>
                );
            }
        });
        return template;
    };

    widget = (type) => {
        const {props, action} = this.comp;
        action.btnAct.changeOrg(type);
    }
    // 初始化
    didMount = () => {
        if (window.location.href.match('localhost:3006')) window.location.hash = '#/ifr?page=201908271034';
        //this.appConfig = getAppPageConfig()
        this.getTemplate();
        this.getLanguage();
        this.comp.action.btnAct.initPageButton();
        // 统一订阅事件
        this.subscribe();
        let type = pageTo.getUrlParam('type')
        console.log(type);
        if (type) {
            setTimeout(() => {
                this.widget(type)
            }, 200);
        }

    };

    // 卸载
    willUnMount = () => {
        this.pubSub.unSubscribe('getMainTableData');
    };

    // 事件订阅部分
    subscribe = () => {
        const {comp: {action}, pubSub} = this;
        pubSub.subscribe('getMainTableData', (...args) => {
            action.tableAct.getMainTableData(...args);
        });
        pubSub.subscribe('getWidgetTableData', (...args) => {
            action.tableAct.getWidgetTableData(...args);
        });
    };

    // 确认查询
    toSearch = () => {
        this.comp.props.dispatch({
            type: 'emp/update',
            payload: {
                init: true
            }
        });
        this.comp.action.tableAct.getMainTableData();
    };

    onCheckAllChange = (e) => {
        const {props, action} = this.comp;
        const {emp, editTable, meta} = props;
        let nowYear = new Date().getFullYear().toString();
        let nowMonth = (new Date().getMonth() + 1).toString();
        let nowDay = new Date().getDate().toString();

        function timeAdd0(str) {
            if (str.length <= 1) {
                str = '0' + str;
            }
            return str;
        }

        nowYear = timeAdd0(nowYear);
        nowMonth = timeAdd0(nowMonth);
        nowDay = timeAdd0(nowDay);
        let dateString = nowYear + '-' + nowMonth + '-' + nowDay;
        // console.log('wofo', e);
        if (e == true) {
            for (let i = 0; i < emp.materialength; i++) {
                // console.log('yunle', editTable.getValByKeyAndIndex('material', i, 'uncommit'));
                if (editTable.getValByKeyAndIndex('material', i, 'uncommit').value == true) {
                    editTable.setValByKeyAndIndex('material', i, 'uncommit', {value: false});
                }
            }
            for (let i = 0; i < emp.materialength; i++) {
                // console.log('wofu', i);
                editTable.setValByKeyAndIndex('material', i, 'isreceive', {value: true});
                editTable.setValByKeyAndIndex('material', i, 'receivedate', {
                    value: dateString,
                    display: dateString,
                    scale: '0'
                });
            }
        } else {
            for (let i = 0; i < emp.materialength; i++) {
                // console.log('wofu', i);
                editTable.setValByKeyAndIndex('material', i, 'isreceive', {value: false});
                editTable.setValByKeyAndIndex('material', i, 'receivedate', {
                    value: null,
                    display: undefined,
                    scale: '0'
                });
            }
        }
    };

    //翻页
    turnPage = (page) => {
        const {props, action} = this.comp;
        const {emp, dispatch} = props;

        if (page === emp.pageInfo.pageIndex) {
            return;
        }

        let pageInfo = {
            ...emp.pageInfo,
            pageIndex: page
        };

        this.pubSub.publish('getMainTableData', {
            pageInfo: pageInfo
        });
    };

    // 改变每页显示条数
    changePageSize = (size) => {
        const {props, action} = this.comp;
        const {emp, dispatch} = props;

        if (size === emp.pageInfo.pageSize) {
            return;
        }

        let pageInfo = {
            ...emp.pageInfo,
            pageSize: size
        };

        dispatch({
            type: 'emp/update',
            payload: {
                pageInfo: pageInfo
            }
        });
        this.pubSub.publish('getMainTableData', {
            pageInfo: pageInfo
        });
    };
}
